//
//  TravelsDetailViewController.m
//  哎游
//
//  Created by 康守帅 on 14-12-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TravelsDetailViewController.h"
#import "TravelsDetailModel.h"
#import "ConnectModel.h"
#import "TravelsDetailTableViewCell.h"
#import "macro.h"
#import "UIImageView+WebCache.h"
#import "TravelDetilHeaderModel.h"
#import "LocationViewController.h"
#import "LoginViewCnntroller.h"
#import "sinaWiboViewController.h"
#import "Masonry.h"
#import "TravelsDataBase.h"
#import "WebColor.h"
#import "Singleton.h"


@interface TravelsDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation TravelsDetailViewController
{
    TravelsDetailModel *_model;
    TravelDetilHeaderModel *_modelHeader;
}

- (void)dealloc
{
    [_ID release];
    [_tableView release];
    [_tableArray release];
    [_travelsListModel release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.tableArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button setBackgroundImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 80, 45)];
    label.text = @"游记详情";
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    self.navigationItem.titleView = label;
    
    //收藏
    [self judgeTravelsExist];
    UIButton *buttonSave = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"login"] isEqualToString:@"yes"]) {
        if (self.isExist == NO) {
            [buttonSave setBackgroundImage:[UIImage imageNamed:@"save2"] forState:UIControlStateNormal];
        } else {
            [buttonSave setBackgroundImage:[UIImage imageNamed:@"save1"] forState:UIControlStateNormal];
        }
    } else {
        [buttonSave setBackgroundImage:[UIImage imageNamed:@"save2"] forState:UIControlStateNormal];
    }
   
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonSave];
   
    [buttonSave addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    
    [label release];
    [button release];
    
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, self.view.frame.size.height / 2 - 90, 60, 60)];
    _imageView.image = [UIImage imageNamed:@"fireLogin.png"];
    _imageView.layer.cornerRadius = 30;
    _imageView.clipsToBounds = YES;
    [self.view addSubview:_imageView];
    
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    rotationAnimation.duration = 2;
    rotationAnimation.RepeatCount = 10000;
    rotationAnimation.cumulative = NO;
    rotationAnimation.removedOnCompletion = NO;
    rotationAnimation.fillMode = kCAFillModeBoth;
    [_imageView.layer addAnimation:rotationAnimation forKey:@"rotation"];
    
    
    
    [self startJson];
}

- (void)startJson
{
    NSString *str2 = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/?gallery_mode=1", self.ID];
    [ConnectModel connectModelWithUrlStr:str2 parmaters:nil finished:^(NSData *data) {
        [_imageView removeFromSuperview];
        NSDictionary *dic2 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _modelHeader = [[TravelDetilHeaderModel alloc] init];
        [_modelHeader setValuesForKeysWithDictionary:dic2];
        
        [self secendJson];
    }];

}


- (void) secendJson
{
    
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/trackpoints/", self.ID];
    [ConnectModel connectModelWithUrlStr:str parmaters:nil finished:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        _model = [[TravelsDetailModel alloc] init];
        [_model setValuesForKeysWithDictionary:dic];
        
        [self.tableArray removeAllObjects];
        
        for (NSArray *arr in _model.trackpoints) {
            if ([arr objectAtIndex:6] == nil || [[arr objectAtIndex:6] isEqualToString:@""]) {
                continue;
            }else {
                [self.tableArray addObject:arr];
            }
        }
        [self createTableView];
    }];

}



#pragma mark - 详情
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 113) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[TravelsDetailTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    //给tableView的HeaderView赋值
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150)];
    _tableView.tableHeaderView = view;

//    [view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.height.mas_equalTo(150);
//        make.width.mas_equalTo(self.view.frame.size.width);
//    }];

    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 12, 44, 44)];

    [imageView sd_setImageWithURL:[NSURL URLWithString:[_modelHeader.user objectForKey:@"avatar_m"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    imageView.layer.cornerRadius = 22;
    imageView.layer.masksToBounds = YES;
    [view addSubview:imageView];
//    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.tableView.tableHeaderView.mas_left).offset(10);
//        make.top.equalTo(self.tableView.tableHeaderView.mas_top).offset(12);
//        make.size.mas_equalTo(CGSizeMake(44, 44));
//    }];

    
    UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, 260, 30)];
    [labelName setText:_name];
    [labelName setTextColor:[UIColor blackColor]];
    [labelName setFont:[UIFont systemFontOfSize:18]];
    [view addSubview:labelName];
//    [labelName mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(imageView.mas_right).offset(10);
//        make.top.equalTo(self.tableView.tableHeaderView.mas_top).offset(10);
//        make.right.equalTo(self.tableView.tableHeaderView.mas_right).offset(-10);
//    }];
    
    UILabel *labelFirstDay = [[UILabel alloc] initWithFrame:CGRectMake(70, 45, 80, 20)];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[_first_day intValue]];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:confromTimesp];
    NSDate *localeDate = [confromTimesp  dateByAddingTimeInterval: interval];
    NSInteger timeOffset = [zone secondsFromGMTForDate:localeDate];
    NSDate *newDate = [localeDate dateByAddingTimeInterval:timeOffset];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy.MM.dd"];
    NSString *dateStr = [dateFormat stringFromDate: newDate];
    [labelFirstDay setText:dateStr];
    labelFirstDay.font = [UIFont systemFontOfSize:13];
    [view addSubview:labelFirstDay];
//    [labelFirstDay mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(imageView.mas_right).offset(15);
//        make.top.equalTo(labelName.mas_bottom).offset(10);
//        make.size.mas_equalTo(CGSizeMake(80, 20));
//    }];
    
    UILabel *labelDayCount = [[UILabel alloc] initWithFrame:CGRectMake(160, 45, 60, 20)];
    NSString *strDayCount = [NSString stringWithFormat:@"%@天", _day_count];
    [labelDayCount setText:strDayCount];
    [labelDayCount setFont:[UIFont systemFontOfSize:13]];
    [view addSubview:labelDayCount];
//    [labelDayCount mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(labelFirstDay.mas_right).offset(20);
//        make.top.equalTo(labelName.mas_bottom).offset(10);
//        make.size.mas_equalTo(CGSizeMake(60, 20));
//    }];
    
    //国家图标
    UIImageView *imageCountry = [[UIImageView alloc] initWithFrame:CGRectMake(12, 77, 40, 28)];
    imageCountry.layer.cornerRadius = 5;
    imageCountry.layer.masksToBounds = YES;
    [view addSubview:imageCountry];

    
    if ([_modelHeader.covered_countries count] == 0 || [_modelHeader.covered_countries objectAtIndex:0] == nil ) {

        [imageCountry sd_setImageWithURL:nil placeholderImage:nil];;
    }else{
        NSDictionary *dic = [_modelHeader.covered_countries objectAtIndex:0];
        NSString *str = [dic objectForKey:@"icon"];

        [imageCountry sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:nil];
    }
    
    NSMutableArray *array = [NSMutableArray array];

    for (NSString *str in _modelHeader.cities) {
        [array addObject:str];
    }
    
    for(int i = 0; i < [array count]; i++){
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(65 * i + 60, 73, 75, 30)];
        label.text = [array objectAtIndex:i];
        [label setFont:[UIFont systemFontOfSize:15]];
        [view addSubview:label];
        [label release];
    }
    UIButton *buttonMap = [[UIButton alloc] initWithFrame:CGRectMake(20, 130, 320, 40)];
    [buttonMap setBackgroundColor:[WebColor mediumSeaGreen]];
    [buttonMap setTitle:@"查看线路" forState:UIControlStateNormal];
    [buttonMap addTarget:self action:@selector(Map) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:buttonMap];
    
    [buttonMap mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.tableView.tableHeaderView.mas_bottom).offset(0);
        make.left.equalTo(self.tableView.tableHeaderView.mas_left).offset(0);
        make.right.equalTo(self.tableView.tableHeaderView.mas_right).offset(0);
    }];

    [buttonMap release];
    [imageView release];
    [labelName release];
    [labelFirstDay release];
    [imageCountry release];
    [labelDayCount release];
    [view release];

    [_tableView release];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_tableArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelsDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    NSMutableArray *array = [_tableArray objectAtIndex:indexPath.row];

    [cell.backImageView sd_setImageWithURL:[NSURL URLWithString:[array objectAtIndex:6]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[[array objectAtIndex:7]  intValue]];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:confromTimesp];
    NSDate *localeDate = [confromTimesp  dateByAddingTimeInterval: interval];
    
    NSInteger timeOffset = [zone secondsFromGMTForDate:localeDate];
    NSDate *newDate = [localeDate dateByAddingTimeInterval:timeOffset];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm"];
    NSString *dateStr = [dateFormat stringFromDate: newDate];
    
    cell.date.text = dateStr;
    cell.backgroundColor = [WebColor seaShell];
    cell.detail.text = [array objectAtIndex:5];
//    [cell changeFrame];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *array = [_tableArray objectAtIndex:indexPath.row];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15.0f], NSFontAttributeName, nil];
    if (IOS_VERSION > 7.0) {
        CGRect rect = [[array objectAtIndex:5] boundingRectWithSize:CGSizeMake(CELL_WIDTH - 30, 1000) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:dic context:nil];
        CGFloat height = rect.size.height + 240 + 15 + 30;
        return height;
    } else {
        CGFloat height = [[array objectAtIndex:5] sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(CELL_WIDTH - 30, 1000)].height;
        return height + 240 + 15 + 30;
    }
}

- (void) Map
{
    LocationViewController *location = [[LocationViewController alloc] init];
    [self.navigationController pushViewController:location animated:YES];
    
    location.locationArray = _model.trackpoints;
    location.countryName = [_modelHeader.cities objectAtIndex:0];
    location.lastCountryName = [_modelHeader.cities lastObject];
    location.name = [_modelHeader.user objectForKey:@"name"];
    location.lastName = [_modelHeader.user objectForKey:@"name"];
    [location release];
}

- (void) myLogin : (id) sender
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"login"] isEqualToString:@"yes"]) {
        sinaWiboViewController *sina = [[sinaWiboViewController alloc] init];
        [self presentViewController:sina animated:YES completion:nil];
        [sina release];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"不好意思哦~" message:@"请先登录哦~" delegate:self cancelButtonTitle:@"登陆" otherButtonTitles:@"取消", nil];
        [alert show];
        [alert release];
    }
}

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        LoginViewCnntroller *login = [[LoginViewCnntroller alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
        [login release];
        [nav release];
    }
}
- (void) returnBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)judgeTravelsExist
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"state"] isEqualToString:@"sina"]) {
        self.isExist = [TravelsDataBase selectForTravelsId:[_travelsListModel.ID stringValue] user:[user objectForKey:@"userSina"]];
    } else if ([[user objectForKey:@"state"] isEqualToString:@"local"]){
        self.isExist = [TravelsDataBase selectForTravelsId:[_travelsListModel.ID stringValue] user:[user objectForKey:@"userName"]];
    }
}

- (void) save : (UIButton *) button
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([[user objectForKey:@"login"] isEqualToString:@"yes"]) {
        if ([[user objectForKey:@"state"] isEqualToString:@"sina"]) {
            [self judgeTravelsExist];
            if (_isExist == NO) {
                [button setImage:[UIImage imageNamed:@"save1.png"] forState:UIControlStateNormal];
                [TravelsDataBase insertIntoUserTravels:_travelsListModel user:[user objectForKey:@"userSina"]];
            } else {
                [button setImage:[UIImage imageNamed:@"save2.png"] forState:UIControlStateNormal];
                [TravelsDataBase deleteFromUserTravels:[_travelsListModel.ID stringValue] user:[user objectForKey:@"userSina"]];
            }

        } else if ([[user objectForKey:@"state"] isEqualToString:@"local"]) {
            [self judgeTravelsExist];
            if (_isExist == NO) {
                [button setImage:[UIImage imageNamed:@"save1.png"] forState:UIControlStateNormal];
                [TravelsDataBase insertIntoUserTravels:_travelsListModel user:[user objectForKey:@"userName"]];
                
            } else {
                [button setImage:[UIImage imageNamed:@"save2.png"] forState:UIControlStateNormal];
                [TravelsDataBase deleteFromUserTravels:[_travelsListModel.ID stringValue] user:[user objectForKey:@"userName"]];
            }
        }
    } else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
